import {messages,queryCurrencyPrecision} from "share/common";
import React from 'react'
import ExportModal from 'components/template/export-modal/export-modal';
import {connect} from 'react-redux'
import { message, Tag, Popover } from 'antd'
import CustomTable from 'components/custom-table'
import moment from 'moment'
import menuRoute from 'routes/menuRoute'
import constants from 'share/constants'
import SearchArea from 'components/search-area'
import financeViewService from 'containers/financial-management/finance-view/finance-view.service'
import borrowService from 'containers/loan-billing/borrow-and-return.service'
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'

class FinanceView extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      searchForm: [
        {
          type: 'searcher',
          id: 'formOIDs',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: {formType: 3001}
        },
        {
          type: 'combobox',
          id: 'userOID',
          label: messages('financial-management.key123'/*申请人姓名/工号*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key123'/*申请人姓名/工号*/),
          options: [],
          searchUrl: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          method: 'get',
          searchKey: 'keyword',
          labelKey: 'fullName',
          valueKey: 'userOID',
          renderOption: option => (`${option.eid}-${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
            `（${option.status === 1002 ? messages('financial-management.key622')/*待离职员工*/ : messages('financial-management.key623')/*离职员工*/}）`
          ) : '')}`)
        }, //申请人姓名/工号
        {
          type: 'combobox', id: 'businessCode', label: messages('financial-management.key234'/*单据ID*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key234'/*单据ID*/),
          options: [], searchUrl: `/api/loanBill/query/business/code/by/keyword?status=`, method: 'get',
          searchKey: 'keyword', getParams: {page: 0, size: 10}, labelKey: '_self', valueKey: '_self'
        }, //父单/子单ID/借款单ID
        {
          type: 'list', id: 'departmentOIDs', label: messages('financial-management.key195'/*部门*/),
          listType: 'department', labelKey: 'name', valueKey: 'departmentOid'
        },
        {
          type: 'items', id: 'dateRange', items: [
            {
              type: 'date',
              id: 'beginDate',
              label: messages('financial-management.key126'/*提交日期从*/),
              defaultValue: moment().subtract(1, 'month')
            }, //提交日期从
            {
              type: 'date',
              id: 'endDate',
              label: messages('financial-management.key127'/*提交日期至*/),
              defaultValue: moment()
            } //提交日期至
          ]
        },
        {
          type: 'items', id: 'approvalDateRange', items: [
            {type: 'date', id: 'approvalStartDate', label: messages('financial-management.key193'/*审批日期从*/)},//审批日期从
            {type: 'date', id: 'approvalEndDate', label: messages('financial-management.key194'/*审批日期至*/)}//审批日期至
          ]
        },
        {
          type: 'items', id: 'auditedApprovalDateRange', items: [
            {type: 'date', id: 'auditedApprovalStartDate', label: messages('financial-management.key236'/*审核日期从*/)},//审核日期从
            {type: 'date', id: 'auditedApprovalEndDate', label: messages('financial-management.key237'/*审核日期从*/)}//审批日期至
          ]
        },
        {
          type: 'select', id: 'currencyCode', label: messages('common.currency'), options: [],
          getUrl: `/api/currency/status/query/by/setOfBooksId?userOId=${props.user.userOID}`,
          labelKey: 'currency', valueKey: 'currency', method: 'get'
        },
        {
          type: 'combobox', id: 'reimbursementBatchOid', label: messages('financial-management.key768')/*付款批次号*/,
          placeholder: messages('common.please.enter') + messages('financial-management.key768')/*付款批次号*/,
          options: [],
          searchUrl: `/api/reimbursement/batch/query/byBatchName?batchType=3001&roleType=TENANT`,
          method: 'get',
          searchKey: 'batchName',
          labelKey: 'reimbursementBatchName',
          valueKey: 'reimbursementBatchOID',
        },
        {
          type: 'checkbox', id: 'status', label: messages('common.column.status'), colSpan: 24, options: [ //状态
            {label: messages('financial-management.key120'/*审批中*/), value: 'submitted'}, //审批中
            {label: messages('financial-management.key121'/*已通过*/), value: 'approval_pass'},  //已通过
            {label: messages('financial-management.key122'/*已驳回*/), value: 'approval_reject'}, //已驳回
            {label: messages('financial-management.key229'/*审核通过*/), value: 'audit_pass'}, //审核通过
            {label: messages('financial-management.key227'/*审核驳回*/), value: 'audit_reject'}, //审核驳回
            {label: messages('financial-management.key232'/*付款中*/), value: 'payment_in_process'}, //付款中
            {label: messages('financial-management.key174'/*已付款*/), value: 'finance_loan'}, //已付款
            {label: messages('financial-management.key230'/*还款中*/), value: 'paid_in_process'}, //还款中
            {label: messages('financial-management.key231'/*已还款*/), value: 'paid_finish'}, //已还款
          ]
        }
      ],
      searchParams: {},
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: 72, render: (text, record, index) => (this.state.page * 10 + index + 1)},  //序号
        {title: messages('financial-management.key130'/*工号*/), dataIndex: 'employeeID'},
        {title: messages('financial-management.key131'/*申请人*/), dataIndex: 'applicant'},
        {title: messages('financial-management.key132'/*提交日期*/), dataIndex: 'lastSubmittedDate',width: 120, render: (date, record) =>
            date ? moment(date).format('YYYY-MM-DD') : moment(record.createDate).format('YYYY-MM-DD'), sorter: true},
        {title: messages('financial-management.key133'/*单据类型*/), dataIndex: 'formName', render: value => <Popover content={value}>{value}</Popover>, sorter: true},
        {title: messages('financial-management.key134'/*单号*/), dataIndex: 'businessCode', render: (value, record) => (
            <Popover content={record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}>
              {record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}
            </Popover>
          ), sorter: true},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 72},
        {title: messages('common.matter')/*事由*/, dataIndex: 'title', render: value => <Popover content={value}>{value}</Popover>},
        {
          title: messages('financial-management.key257')/*借款金额*/,
          dataIndex: 'totalAmount',
          align: "right",
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
          sorter: true
        },
        {title: messages('financial-management.key170'/*凭证编号*/), dataIndex: 'origDocumentSequence', width: '10%', render: value => <Popover content={value} placement="topLeft">{value}</Popover>},
        {title: messages('common.column.status'), dataIndex: 'status', width: this.props.language.code === 'zh_cn' ? '8%' : '13%', render: (value, record) => {
            let applicationType = '';
            (+record.entityType === 1008) && (applicationType = 2005);//申请单下的applicationType是2005
            let text;
            let color;
            text = constants.getTextByValue(String(value + '' + applicationType), 'documentLoanStatus') ||
              constants.getTextByValue(String(value + '' + record.rejectType), 'documentLoanStatus') ||
              constants.getTextByValue(String(value), 'documentLoanStatus');
            color = constants.getTextByValue(String(value + '' + applicationType), 'documentLoanStatus', 'color') ||
              constants.getTextByValue(String(value + '' + record.rejectType), 'documentLoanStatus', 'color') ||
              constants.getTextByValue(String(value), 'documentLoanStatus', 'color')
            return <Tag color={color} >{text}</Tag>
          }},
        //状态
        {title: messages('common.operation'), dataIndex: 'operation', width: this.props.language.code === 'zh_cn' ? '7%' : '10%', render: (value, record) =>
            <a onClick={event => this.print(record, event)}>{messages('financial-management.key137'/*打印*/)}</a>}
      ],
      data: [],
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      sort: '',
      pageSize: 10,
      page: 0,
      loanDetailView: menuRoute.getRouteItem('loan-detail-view', 'key'),
    }
  }

  componentDidMount(){
    this.getList(true);
  };

  getList = (firstRequest) => {
    const { page, pageSize, searchParams, sort, pagination } = this.state;
    if (firstRequest) {
      searchParams.beginDate = moment().subtract(1, 'month').format('YYYY-MM-DD 00:00:00');
      searchParams.endDate = moment().format('YYYY-MM-DD 23:59:59');
    }
    searchParams.entityType = 1008;
    this.setState({ loading: true });
    if(sort) {
      searchParams.sorts = {
        property: sort.split(',')[0],
        direction: sort.split(',')[1]
      };
    }
    if(pagination.total !== 0){
      searchParams.total = pagination.total;
    };
    let isAudit = '1';
    financeViewService.getFinanceViewList(page, pageSize, searchParams, isAudit).then(res => {
      if (res.status === 200) {
        pagination.total = Number(res.headers['x-total-count']);
        pagination.current = page + 1;
        this.setState({
          loading: false,
          data: res.data,
          pagination
        })
      }
    }).catch((e) => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.pageSize)
      this.setState({
        page: 0,
        pageSize: size
      })
  };

  search = (result) => {
    let { searchParams }=this.state;
    result.beginDate && (result.beginDate = moment(result.beginDate).format('YYYY-MM-DD 00:00:00'));
    result.endDate && (result.endDate = moment(result.endDate).format('YYYY-MM-DD 23:59:59'));
    result.approvalStartDate && (result.approvalStartDate = moment(result.approvalStartDate).format('YYYY-MM-DD 00:00:00'));
    result.approvalEndDate && (result.approvalEndDate = moment(result.approvalEndDate).format('YYYY-MM-DD 23:59:59'));
    result.auditedApprovalStartDate && (result.auditedApprovalStartDate = moment(result.auditedApprovalStartDate).format('YYYY-MM-DD 00:00:00'));
    result.auditedApprovalEndDate && (result.auditedApprovalEndDate = moment(result.auditedApprovalEndDate).format('YYYY-MM-DD 23:59:59'));
    result.printFree === 'null' && (delete result.printFree);
    result.searchCorporations = result.legalEntity ? result.legalEntity :[];
    result.searchCostCenterCommands = searchParams.searchCostCenterCommands;
    this.setState({
      searchParams: result,
      page: 0
    }, () => {
      this.getList();
    })
  };

  clear = () => {
    this.handleSearchData();
    this.setState({ searchParams: {} },() => {
      this.getList();
    })
  };

  handleSearchData = () => {
    let {searchForm} = this.state;
    let dateRange=searchForm.filter(item => item.id === 'dateRange')[0];
    dateRange.items[0].defaultValue = null;
    dateRange.items[1].defaultValue = null;
    this.setState({searchForm})
  };

  handleRowClick = (record) => {
    this.context.router.push(this.state.loanDetailView.url.replace(':formOID', record.formOID).replace(':loanBillOID', record.entityOID))
  };

  print = (record,event) => {
    event.preventDefault();
    event.stopPropagation();
    event.cancelBubble = true;
    if (record.entityType === 1002) {
      financeViewService.printExpenseReport(record.entityOID).then(res => {
        window.open(res.data.fileURL, '_blank');
      })
    } else {
      borrowService.printLoanApplication(record.entityOID).then(res => {
        window.open(res.data.link, '_blank')
      })
    }
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page =  pagination.current;
    let sort = '';
    if(sorter.order){
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      sort
    }, ()=>{
      this.getList();
    })
  };

  renderExpandedRow = (title, content) => {
    return (
      <div>
        <span>{title}</span>
        {content && <span>:{content}</span>}
      </div>
    )
  };

  renderAllExpandedRow = (record) => {
    let result = [];
    if(record.printFree){
      result.push(this.renderExpandedRow(messages('common.print.free'), messages('common.print.require')));
    }
    return result.length > 0 ? result : null;
  };

  changeCostCenter = (value) => {
    const { searchParams } = this.state;
    searchParams.searchCostCenterCommands = value;
    this.setState({searchParams})
  };

  render() {
    const { loading, searchForm, columns, data, pagination, searchParams } = this.state;
    return (
      <div className="finance-view">
        <SearchArea searchForm={searchForm}
                    submitHandle={this.search}
                    clearHandle={this.clear}
                    extraFieldsIndex={7}
                    extraFields={[
                      <div>
                        <div style={{lineHeight: '28px'}}>
                          {messages('financial-management.key145'/*成本中心*/)}
                        </div>
                        <CostCenterSearchForm title={messages('financial-management.key145'/*成本中心*/)}
                                              value={searchParams.searchCostCenterCommands}
                                              onChange={this.changeCostCenter}/>
                      </div>
                    ]}/>
        <div className="table-header">
          <div className="table-header-buttons">
            {/* <ExportModal
              type={"btn"}
              exportTitle={messages('financial-management.key146')}
              exportType="BILL_CHECK"
              exportCondition={{
                billCheckSearchCommand: this.state.searchParams
              }}
              exportCommand={'EXP_OR_LOANBILL'}/> */}
          </div>
          <div className="table-header-title">{messages('common.total',{total: pagination.total || 0})}</div>
          {/*共多少条数据*/}
        </div>
        <CustomTable allColumns={columns}
                     localKey="finance-loan-view"
                     tableOption={{
                       rowKey: record => record.entityOID,
                       loading,
                       rowSelection: null,
                       pagination,
                       columns,
                       expandedRowRender: this.renderAllExpandedRow,
                       onChange: this.handleTableChange,
                       onRow: record => ({
                         onClick: () => this.handleRowClick(record)
                       }),
                       rowClassName: record => record.printFree ? '' : 'row-expand-display-none',
                       bordered: true,
                       dataSource: data
                     }}/>
      </div>
    )
  }
}

FinanceView.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(FinanceView);
